const htmlparser2 = require("htmlparser2");
const fs = require('fs');
const path = require('path');

//#region 资源页面解析
let code = fs.readFileSync(path.resolve(__dirname, `./demo/demo3.html`), { encoding: 'utf-8' });
const dom = htmlparser2.parseDocument(code);
const resources = htmlparser2.DomUtils.findAll(element => {
    const matches = element.name === 'article' && element.attribs.class === 'excerpt excerpt-one';
    return matches;
}, dom.children);
let currentPageSource = []
let nextPageUrl = ''
let prevPageUrl = ''
const nextPageEl = htmlparser2.DomUtils.findOne(e => e.name === 'li' && e.attribs.class === 'next-page', dom.children);
if (nextPageEl) {
    const nextAEl = htmlparser2.DomUtils.findOne(e => e.name === 'a', nextPageEl.children);
    if (nextAEl) {
        nextPageUrl = '/' + nextAEl.attribs.href;
    }
}
const prevPageEl = htmlparser2.DomUtils.findOne(e => e.name === 'li' && e.attribs.class === 'prev-page', dom.children);
if (prevPageEl) {
    const prevAEl = htmlparser2.DomUtils.findOne(e => e.name === 'a', prevPageEl.children);
    if (prevAEl) {
        prevPageUrl = '/' + prevAEl.attribs.href;
    }
}

resources.forEach(resource => {
    const header = htmlparser2.DomUtils.findOne(e => e.name === 'header', resource.children)
    let title = ''
    let url = ''
    let img = ''
    if (header) {
        let aEl = htmlparser2.DomUtils.findOne(e => e.name === 'a' && e.attribs.target === '_blank', header.children)
        if (aEl) {
            title = aEl.attribs.title
            url = aEl.attribs.href
        }
    }
    let imgEl = htmlparser2.DomUtils.findOne(e => e.name === 'img', resource.children)
    if (imgEl) {
        img = imgEl.attribs.src
    }
    currentPageSource.push({
        title, url, img
    })
})
console.log(`本页共${currentPageSource.length}个资源`)
console.log(currentPageSource)
console.log(`上一页：${prevPageUrl}`)
console.log(`下一页：${nextPageUrl}`)
//#endregion


debugger;
//#region 详情页面解析
let codeDetail = fs.readFileSync(path.resolve(__dirname, `./demo/demo4.html`), { encoding: 'utf-8' });

console.time("codeDetail")
const detailDom = htmlparser2.parseDocument(codeDetail);
console.timeEnd("codeDetail")
// console.log(detailDom)

//#region 本页图片解析
const imgUrls = []
const detailResourceArticleEl = htmlparser2.DomUtils.findOne(element => {
    const matches = element.name === 'article' && element.attribs.class === 'article-content';
    return matches;
}, detailDom.children);
if (detailResourceArticleEl) {
    htmlparser2.DomUtils.findAll(element => {
        if (element.name === 'img') {
            imgUrls.push(element.attribs.src)
        }
        return true
    }, detailResourceArticleEl.children);
}
//#endregionf

//#region 下一页url解析

let detailNextPageUrl = ''

const detailNextPageEl = htmlparser2.DomUtils.findOne(e => e.name === 'li' && e.attribs.class === 'next-page', detailDom.children);
if (detailNextPageEl) {
    const nextAEl = htmlparser2.DomUtils.findOne(e => e.name === 'a', nextPageEl.children);
    if (nextAEl) {
        detailNextPageUrl = '/' + nextAEl.attribs.href;
    }
}
//#endregion 
console.log(`本页共${imgUrls.length}个图片`)
console.log(imgUrls)
console.log(`下一页：${detailNextPageUrl}`)

//#endregion





// let out = {
//     type: dom.type,
//     children: []
// }

// children
//     name data
// type tag text
// let cur = dom.children
// let o = out.children
// while (cur) {
//     let child = cur
//     for (let item of child) {
//         if (item.type === "tag") {
//             o.push({name: item.name, type: item.type})
//         } else if (item.type === "text") {
//             o.push({data: item.data, type: item.type})
//         }
//     }
//     cur = child.children
//     o.children = []
// }

// let copy = {}

// let out = []
// let stack = [dom]

// let cur = stack.shift()
// while (cur) {
//     console.log(cur)
//     if (cur.type === "tag") {
//         out.push({name: cur.name, type: cur.type})
//     } else if (cur.type === "text") {
//         out.push({data: cur.data, type: cur.type})
//     } else if (cur.type === "root") {
//         out.push({type: cur.type})
//     }
//     if (cur.children) {
//         stack.push(... cur.children)
//     }
//     cur = stack.shift()
// }

// fs.writeFileSync(path.resolve(__dirname, "./demo.html.json"), stringify(out))

// console.log(dom)

// // 选择节点
// let ele = htmlparser2.DomUtils.getElementById("out", dom.children)

// console.log(ele)

// // 节点style属性
// let styles = ele.attribs.style.split(";").filter(item => item)

// console.log(styles)

// // style样式
// let stylesStruct = {}

// for (let i = 0; i < styles.length; i++) {
//     let item = styles[i].split(":")
//     let attr = item[0]
//     let value = item[1]
//     stylesStruct[attr] = value
// }


// console.log(stylesStruct)

// // 修改style样式
// stylesStruct['display'] = "none"

// let newStyle = ""

// // 拼接修改后的样式
// for (let attr in stylesStruct) {
//     let item = [
//         attr, stylesStruct[attr]
//     ].join(":")
//     newStyle += `${item};`
// }

// // 还原修改后的样式
// ele.attribs.style = newStyle

// console.log(dom)

// // 渲染为HTML文本
// let ss = render(dom)

// console.log(ss)
